
package com.luffy.devops


def init(String project, String receiver, String credentialsId, String title) {
    this.project = project                      //项目名称用来组装消息
    this.receiver = receiver                    //消息发送平台 dingTalk，wechat
    this.credentialsId = credentialsId          //获取dingTalk等消息平台在Jenkins中存的Token等保密信息
    this.title = title                          //组装消息的标题
    return this
}


def notification(String type){
    /**
     * 流水线通知成功/失败，只有标题有区别，其他信息都一致
     */
    String msg ="😄👍 ${this.title} 👍😄"

    if (this.title == "") {
        msg = "😄👍 流水线成功啦 👍😄"
    }

    if (type == "failure") {
        msg ="😖❌ ${this.title} ❌😖"
        if (this.title == "") {
            msg = "😖❌ 流水线失败了 ❌😖"
        }
    }

    String title = msg

    msg = genNotificationMessage(msg)
    if( this.receiver == "dingTalk") {
        try {
            new DingTalk().markDown(title, msg, this.credentialsId)
        } catch (Exception ignored) {
            echo "发送钉钉消息失败。。。。。"
        }
    }else if(this.receiver == "wechat") {

        //todo

    }else if (this.receiver == "email"){

        //todo

    }else{

        error "不支持通知类型!"

    }
}


def genNotificationMessage(msg) {

    msg = "${msg}  \n  **项目名称** : ${this.project}"

    def gitlog = ""
    try {
        sh "git log --oneline -n 1 > gitlog.file"
        gitlog = readFile "gitlog.file"
    } catch (Exception ignored) {}

    if (gitlog != null && gitlog != "") {
        msg = "${msg}  \n  **Git log**       : ${gitlog}"
    }

    def gitbranch = env.BRANCH_NAME
    if (gitbranch != null && gitbranch != "") {
        msg = "${msg}  \n  **Git branch** : ${gitbranch}"
    }

    msg = "${msg}  \n  **Build Tasks**: ${env.BUILD_TASKS}"

    msg = "${msg}  \n  **流水线**    : ${env.RUN_DISPLAY_URL}"

    msg = "${msg}  \n  **代码扫描** : http://sonar.luffy.com/dashboard?id=${this.project} \n"

//    msg = msg + getButtonMsg()

    return msg
}


def getButtonMsg(){
    String res = ""
    def  buttons = [
            [
                    "title": "查看流水线",
                    "actionURL": "${env.RUN_DISPLAY_URL}"
            ],
            [
                    "title": "代码扫描结果",
                    "actionURL": "http://sonar.luffy.com/dashboard?id=${this.project}"
            ]
    ]
    buttons.each() {
        if(res == ""){
            res = "   \n >"
        }
        res = "${res}   [" +it[ "title" ]+ "](" +it[  "actionURL"]+  ") "
    }
    return res
}